import 'package:bruno/bruno.dart';
import 'package:dio/dio.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:sp_util/sp_util.dart';
import '../../../api/LoginApi.dart';
import '../../../api/auth/AuthBase.dart';
import '../../../home/AppLocale.dart';
import '../../../res/constant.dart';
import '../../../res/gaps.dart';
import '../../../res/styles.dart';
import '../../../routers/fluro_navigator.dart';
import '../../../tools/widgets/my_app_bar.dart';
import '../../../tools/widgets/my_button.dart';
import '../../../tools/widgets/my_scroll_view.dart';
import '../../../utils/change_notifier_manage.dart';
import '../../../utils/other_utils.dart';
import '../../../utils/toast_utils.dart';
import '../../my/x_user_router.dart';
import '../login_router.dart';
import '../widgets/my_text_field.dart';

/// design/1注册登录/index.html
class SMSLoginPage extends StatefulWidget {
  const SMSLoginPage({super.key});

  @override
  _SMSLoginPageState createState() => _SMSLoginPageState();
}

class _SMSLoginPageState extends State<SMSLoginPage> with ChangeNotifierMixin<SMSLoginPage> {
  // 定义一个controller
  final TextEditingController _nameController = TextEditingController();
  final TextEditingController _passwordController = TextEditingController();
  final TextEditingController _vCodeController = TextEditingController();
  final FocusNode _nodeText1 = FocusNode();
  final FocusNode _nodeText2 = FocusNode();
  bool _clickable = false;
  bool isLoading = false;
  bool isAgreed = true;

  late String codeRegister = "";

  final LoginApi _loginApi = LoginApi();

  @override
  Map<ChangeNotifier, List<VoidCallback>?>? changeNotifier() {
    final List<VoidCallback> callbacks = <VoidCallback>[_verify];
    return <ChangeNotifier, List<VoidCallback>?>{
      _nameController: callbacks,
      _vCodeController: callbacks,
      _nodeText1: null,
      _nodeText2: null,
    };
  }

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      /// 显示状态栏和导航栏
      SystemChrome.setEnabledSystemUIMode(SystemUiMode.manual, overlays: [SystemUiOverlay.top, SystemUiOverlay.bottom]);
    });
    _nameController.text = SpUtil.getString(Constant.phone).nullSafe;
  }

  void _verify() {
    final String name = _nameController.text;
    // final String password = _passwordController.text;
    final String code = _vCodeController.text;
    bool clickable = true;
    if (name.isEmpty || name.length < 1) {
      clickable = false;
    }
    // if (password.isEmpty || password.length < 1) {
    //   clickable = false;
    // }
    if (code.isEmpty || code.length < 4) {
      clickable = false;
    }
    

    // 新增：检查是否同意协议
    if (!isAgreed) {
      clickable = false;
    }

    /// 状态不一样再刷新，避免不必要的setState
    if (clickable != _clickable) {
      setState(() {
        _clickable = clickable;
      });
    }
  }

  Future<void> _codeLogin() async {
    if (!isAgreed) {
      Toast.show(AppLocale.text('lg_qingtongyizhengce'));
      return;
    }

    SpUtil.putString(Constant.phone, _nameController.text);

    // 显示加载状态
    setState(() {
      isLoading = true;
    });

    try {
      //判断验证码
      if(_vCodeController.text != codeRegister){
        Toast.show(AppLocale.text('lg_yanzhegnmacuowu'));
      }else{

        final toUpdate = {
          "username": _nameController.text,
        };
        final response = await _loginApi.codeLogin(toUpdate);

        if (response.code == 200) {

          //返回上一页面
          // NavigatorUtils.goBack(context);

          //保存token跳转首页
          await AuthBase().saveToken(response.data);
          Navigator.pushNamed(context, "/home");


        } else {
          Toast.show(AppLocale.text('lg_denglushibai') +
              "${response.getMsg ?? AppLocale.text('lg_weizhicuowu')}");
        }
      }

    } catch (e) {
      // 处理异常
      print('登录异常: $e');
      Toast.show(AppLocale.text('lg_wangluocuowu'));
    } finally {
      // 隐藏加载状态
      setState(() {
        isLoading = false;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: MyAppBar(
        isBack: true,
        // actionName: '验证码登录',
        onPressed: () {
          // NavigatorUtils.push(context, LoginRouter.smsSMSLoginPage);
        },
      ),
      body: Stack(
        children: [
          AbsorbPointer(
            absorbing: isLoading,
            child: Column(
              children: [
                // 上方部分：标题、验证码登录切换
                Container(
                  width: double.infinity,
                  padding: const EdgeInsets.only(left: 32.0, right: 32.0, top: 1),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        AppLocale.text('lg_yanzhegnmadenglu'),
                        style: TextStyles.textBold26,
                      ),

                      Gaps.vGap24,
                    ],
                  ),
                ),
                // 下方白色背景包裹部分（高度延伸到底部）

                const SizedBox(height: 20,),


                Expanded(
                  child: Container(
                    width: double.infinity,
                    decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius: const BorderRadius.vertical(top: Radius.circular(32)),
                    ),
                    padding: const EdgeInsets.symmetric(horizontal: 32.0, vertical: 20.0),
                    child: MyScrollView(
                      keyboardConfig: Utils.getKeyboardActionsConfig(context, <FocusNode>[_nodeText1, _nodeText2]),
                      children: [
                        const SizedBox(height: 10,),


                        MyTextField(
                          backgroundColor: const Color(0xFFF5F8FF),
                          key: const Key('phone'),
                          focusNode: _nodeText1,
                          controller: _nameController,
                          maxLength: 11,
                          keyboardType: TextInputType.phone,
                          hintText: AppLocale.text('lg_qingshrushoujihao'),
                        ),
                        Gaps.vGap24,

                        // MyTextField(
                        //   backgroundColor: const Color(0xFFF5F8FF),
                        //   key: const Key('password'),
                        //   keyName: 'password',
                        //   focusNode: _nodeText2,
                        //   isInputPwd: true,
                        //   controller: _passwordController,
                        //   keyboardType: TextInputType.visiblePassword,
                        //   hintText: '请输入密码',
                        // ),

                        MyTextField(
                          backgroundColor: const Color(0xFFF5F8FF),
                          key: const Key('vcode'),
                          focusNode: _nodeText2,
                          controller: _vCodeController,
                          keyboardType: TextInputType.number,
                          getVCode: () async {
                            if (_nameController.text.length == 11) {

                              final toUpdate = {
                                "phone": _nameController.text
                              };
                              final response = await _loginApi.setCodeRegister(toUpdate);

                              if (response.code == 200) {
                                codeRegister = response.data;
                              }


                              return true;
                            } else {
                              Toast.show(AppLocale.text('lg_qingshruyouxiaoshoujihao'));
                              return false;
                            }
                          },
                          maxLength: 6,
                          hintText: AppLocale.text('lg_qingshuruyanzhegnma'),
                        ),


                        Gaps.vGap24,
                        // 嵌入协议组件
                        Row(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            GestureDetector(
                              onTap: () {
                                setState(() {
                                  isAgreed = !isAgreed;
                                  _verify();
                                });
                              },
                              child: Container(
                                width: 16,
                                height: 16,
                                decoration: BoxDecoration(
                                  border: Border.all(color: const Color(0xFFCCCCCC), width: 1),
                                  borderRadius: BorderRadius.circular(10),
                                  color: isAgreed ? const Color(0xFF007AFF) : Colors.white,
                                ),
                                child: isAgreed
                                    ? const Icon(
                                  Icons.check,
                                  size: 12,
                                  color: Colors.white,
                                )
                                    : null,
                              ),
                            ),
                            const SizedBox(width: 5),
                            Expanded(
                              child: RichText(
                                text: TextSpan(
                                  style: const TextStyle(
                                    color: Color(0x80333333),
                                    fontSize: 12,
                                    height: 1.4,
                                  ),
                                  children: [
                                    TextSpan(text: AppLocale.text('lg_yiyuedubingtingyi')),
                                    TextSpan(
                                      text: AppLocale.text('lg_yonghuxieyi'),
                                      style: const TextStyle(color: Color(0xFF007AFF)),
                                      recognizer: TapGestureRecognizer()
                                        ..onTap = () {
                                          NavigatorUtils.push(
                                            context,
                                            '${XUserRouter.userUseAuth}',
                                          );
                                        },
                                    ),
                                    TextSpan(text: AppLocale.text('lg_he')),
                                    TextSpan(
                                      text: AppLocale.text('lg_yinsizhengce'),
                                      style: const TextStyle(color: Color(0xFF007AFF)),
                                      recognizer: TapGestureRecognizer()
                                        ..onTap = () {
                                          NavigatorUtils.push(
                                            context,
                                            '${XUserRouter.userHideAuth}',
                                          );
                                        },
                                    ),
                                  ],
                                ),
                              ),
                            ),
                          ],
                        ),

                        const SizedBox(height: 25,),

                        MyButton(
                          key: const Key('login'),
                          onPressed: _clickable ? _codeLogin : null,
                          text: AppLocale.text('lg_dengluhuozhucedengl'),
                          radius: 10,
                        ),
                        Gaps.vGap24,
                        Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            GestureDetector(
                              child: Text(
                                AppLocale.text('lg_zhucezhanghao'),
                                key: const Key('noAccountRegister'),
                                style: TextStyle(
                                  // color: const Color(0xFF007AFF),
                                  color: const Color(0xAA2A2A2A),
                                  fontSize: 12,
                                ),
                              ),
                              onTap: () => NavigatorUtils.push(context, LoginRouter.registerPage),
                            ),
                            Container(
                              margin: const EdgeInsets.symmetric(horizontal: 16),
                              height: 16,
                              width: 1,
                              color: Colors.grey,
                            ),
                            GestureDetector(
                              child: Text(
                                AppLocale.text('lg_wangjimima'),
                                key: const Key('forgotPassword'),
                                style: TextStyle(
                                  // color: const Color(0xFF007AFF),
                                  color: const Color(0xAA2A2A2A),
                                  fontSize: 12,
                                ),
                              ),
                              onTap: () => NavigatorUtils.push(context, LoginRouter.resetPasswordPage),
                            ),
                          ],
                        ),
                        const SizedBox(height: 70),



                        // Center(
                        //   child: Row(
                        //     mainAxisAlignment: MainAxisAlignment.center,
                        //     children: [
                        //       Text(
                        //         '—————',
                        //         style: TextStyle(color: Colors.black12),
                        //       ),
                        //       GestureDetector(
                        //         child: Text(
                        //           AppLocale.text('lg_qitadneglufangshi'),
                        //           style: TextStyle(
                        //             color: Colors.black54,
                        //             fontSize: 12,
                        //           ),
                        //         ),
                        //         onTap: () {},
                        //       ),
                        //       Text(
                        //         '—————',
                        //         style: TextStyle(color: Colors.black12),
                        //       ),
                        //     ],
                        //   ),
                        // ),
                        //
                        // const SizedBox(height: 20),
                        // GestureDetector(
                        //   child: Row(
                        //     mainAxisAlignment: MainAxisAlignment.center,
                        //     children: [
                        //       const Icon(
                        //         Icons.wechat,
                        //         color: Colors.green,
                        //         size: 40,
                        //       ),
                        //     ],
                        //   ),
                        //   onTap: () {
                        //
                        //   },
                        // ),


                        const SizedBox(height: 40), // 底部留白
                      ],
                    ),
                  ),
                ),
              ],
            ),
          ),
          if (isLoading)
            Container(
              child: Center(
                child: CircularProgressIndicator(),
              ),
            ),
        ],
      ),
    );
  }
}